//
//  UserModel.m
//  youyue
//
//  Created by oceans on 2018/8/16.
//

#import "UserModel.h"
#import "HttpRequest.h"
#import "AppDelegate.h"
#import <RongIMKit/RongIMKit.h>
#import "ChangePhoneSecondViewController.h"
#import "TipManager.h"

@interface UserModel ()

@property (copy, nonatomic) LoginSuccessBlock thirdLoginSuccess;
@property (copy, nonatomic) LoginFailedBlock thirdLoginFailed;
@end

@implementation LoginUser

- (instancetype)initWithDic:(NSDictionary *)dic {
    self = [super init];
    if (self) {
        [self setup:dic];
    }
    return self;
}

- (void)setup:(NSDictionary *)dic {
    
    _avatar = [dic objectForKey:@"avatar"];
    _birthday = [dic objectForKey:@"birthday"];
    _children = [[dic objectForKey:@"children"] intValue];
    _cover = [dic objectForKey:@"cover"];
    _gender = [[dic objectForKey:@"gender"] intValue];
    _grade = [[dic objectForKey:@"grade"] intValue];
    _hobby = [dic objectForKey:@"hobby"];
    __id = [[dic objectForKey:@"id"] intValue];
    _string_id = [NSString stringWithFormat:@"%@", [dic objectForKey:@"id"]];
    _location = [dic objectForKey:@"location"];
    _marriage = [[dic objectForKey:@"marriage"] intValue];
    _nation = [dic objectForKey:@"nation"];
    _nickname = [dic objectForKey:@"nickname"];
    _realname = [dic objectForKey:@"realname"];
    _register_time = [dic objectForKey:@"register_time"];
    _role_id = [[dic objectForKey:@"role_id"] intValue];
    _signature = [dic objectForKey:@"signature"];
    _teach_scopes = [dic objectForKey:@"teach_scopes"];
    _rongyun_token = [dic objectForKey:@"rongyun_token"];
    _mobile = [dic objectForKey:@"mobile"];
}

- (NSString *)hobyString {
    
    if (_hobby.count == 0) {
        return @"";
    }else if (_hobby.count == 1) {
        return _hobby[0];
    }else if (_hobby.count == 2) {
        return [NSString stringWithFormat:@"%@，%@", _hobby[0], _hobby[1]];
    }else {
        return [NSString stringWithFormat:@"%@，%@等共%ld种", _hobby[0], _hobby[1], _hobby.count];
    }
}

- (NSString *)scopeString {
    if (_teach_scopes.count == 0) {
        return @"";
    }else if (_teach_scopes.count == 1) {
        return _teach_scopes[0];
    }else if (_teach_scopes.count == 2) {
        return [NSString stringWithFormat:@"%@，%@", _teach_scopes[0], _teach_scopes[1]];
    }else {
        return [NSString stringWithFormat:@"%@，%@等共%ld种", _teach_scopes[0], _teach_scopes[1], _teach_scopes.count];
    }
}

- (NSString *)nameString {
    return _nickname;
}

- (NSString *)realname {
    
    if (_realname == nil || (NSNull*)_realname == [NSNull null]) {
        return @"";
    }
    return _realname;
}

- (NSString *)birthday {
    
    if (_birthday == nil || (NSNull*)_birthday == [NSNull null]) {
        return @"";
    }
    return _birthday;
}

@end

@interface UserModel () <TencentSessionDelegate>

@property (strong, nonatomic) TencentOAuth *oauth;
@end

static UserModel *shared;

@implementation UserModel

+ (instancetype)shared {
    
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        shared = [[UserModel alloc] init];
    });
    return shared;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        shared = [super allocWithZone:zone];
    });
    return shared;
}

- (id)copyWithZone:(NSZone *)zone {
    return shared;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self checkUser];
    }
    return self;
}

- (void)checkUser {
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSData *data = [def objectForKey:@"klogin_user_dic_data"];
    NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    if (dic) {
        self.loginUser = [[LoginUser alloc] initWithDic:dic];
        self.hasLogin = YES;
        self.userType = self.loginUser.role_id;
        [self autoLogin];
    }
}

- (void)cacheUser:(NSDictionary*)dic {
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
    [def setObject:data forKey:@"klogin_user_dic_data"];
    [def synchronize];
}

- (void)loginWithPassword:(NSString *)password username:(NSString *)username successBlock:(LoginSuccessBlock)successBlock {
    
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:klogin_pass paras:@{@"username": username, @"password": password} showProgress:YES successful:^(id  _Nullable result) {
        [weakself loginWithDic:[result objectForKey:@"data"]];
        if (successBlock) {
            successBlock();
        }
    } failed:nil];
}

- (void)loginWithCode:(NSString *)code username:(NSString *)username successBlock:(LoginSuccessBlock)successBlock {
    
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:kmobile_login paras:@{@"mobile": username, @"code": code} showProgress:YES successful:^(id  _Nullable result) {
        [weakself loginWithDic:[result objectForKey:@"data"]];
        if (successBlock) {
            successBlock();
        }
    } failed:nil];
}

- (void)getCodeWithPhoneNumber:(NSString *)phone scope:(NSString *)scope successBlock:(LoginSuccessBlock)successBlock failedBlock:(LoginFailedBlock)failedBlock{
    
    [HttpRequest postURL:kget_code paras:@{@"mobile": phone, @"scope": scope} showProgress:NO successful:^(id  _Nullable result) {
        if (successBlock) {
            successBlock();
        }
    } failed:^(int code, NSString *errMsg) {
        if (failedBlock) {
            failedBlock();
        }
    }];
}

- (void)registerWithName:(NSString *)userName code:(NSString *)code password:(NSString *)password successBlock:(LoginSuccessBlock)successBlock {
    
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:kregister paras:@{@"mobile": userName, @"code": code, @"password": password} showProgress:YES successful:^(id  _Nullable result) {
        [weakself loginWithDic:[result objectForKey:@"data"]];
        if (successBlock) {
            successBlock();
        }
    } failed:nil];
}

- (void)findPassword:(NSString *)userName code:(NSString *)code password:(NSString *)password successBlock:(LoginSuccessBlock)successBlock {
    
    [HttpRequest postURL:kfind_password paras:@{@"mobile": userName, @"captcha": code, @"password": password} showProgress:YES successful:^(id  _Nullable result) {
        if (successBlock) {
            successBlock();
        }
    } failed:nil];
}

- (void)bindingNewPhone:(NSString *)phone code:(NSString *)code successBlock:(LoginSuccessBlock)successBlock {
    
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:kbinding_phone paras:@{@"mobile": phone, @"code": code} showProgress:YES successful:^(id  _Nullable result) {
        [weakself loginWithDic:result[@"data"]];
        if (successBlock) {
            successBlock();
        }
    } failed:nil];
}

- (void)resetPassword:(NSString *)password successBlock:(LoginSuccessBlock)successBlock {
    
    [HttpRequest postURL:kreset_password paras:@{@"password": password} showProgress:YES successful:^(id  _Nullable result) {
        if (successBlock) {
            successBlock();
        }
    } failed:nil];
}

- (void)updateUserinfo:(NSString *)infoName value:(id)value successBlock:(LoginSuccessBlock)successBlock {
    
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:kupdate_userinfo paras:@{infoName: value} showProgress:NO successful:^(id  _Nullable result) {
        [weakself loginWithDic:result[@"data"]];
        if (successBlock) {
            successBlock();
        }
    } failed:nil];
}

- (void)autoLogin {
    
    __weak typeof(self) weakself = self;
    [HttpRequest getURL:kauto_login paras:nil showProgress:NO successful:^(id  _Nullable result) {
        [weakself loginWithDic:[result objectForKey:@"data"]];
    } failed:^(int code, NSString *errMsg) {
        [weakself clearWhenLogout];
    }];
}

- (void)loginWithDic:(NSDictionary *)userInfo {
    if (!(userInfo == nil || (NSNull*)userInfo == [NSNull null])) {
        self.loginUser = [[LoginUser alloc] initWithDic:userInfo];
        [self cacheUser:userInfo];
        self.hasLogin = YES;
        self.userType = self.loginUser.role_id;
        [self rongyunLogin];
        [[NSNotificationCenter defaultCenter] postNotificationName:klogin_notification object:nil];
    }
}

- (void)rongyunLogin {
    
    __weak typeof(self) weakself = self;
    [[RCIM sharedRCIM] connectWithToken:self.loginUser.rongyun_token     success:^(NSString *userId) {
        NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
        [RCIM sharedRCIM].globalNavigationBarTintColor = [UIColor redColor];
        [RCIM sharedRCIM].currentUserInfo = [[RCUserInfo alloc] initWithUserId:userId name:weakself.loginUser.nickname portrait:weakself.loginUser.avatar];
    } error:^(RCConnectErrorCode status) {
        NSLog(@"登陆的错误码为:%ld", status);
    } tokenIncorrect:^{
        //token过期或者不正确。
        //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
        //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
        NSLog(@"token错误");
    }];
}

- (void)rongyunLogout {
    [[RCIM sharedRCIM] logout];
}

- (void)clearWhenLogout {
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def removeObjectForKey:@"klogin_user_dic_data"];
    [def synchronize];
    self.hasLogin = NO;
    self.loginUser = nil;
    [self rongyunLogout];
    [[NSNotificationCenter defaultCenter] postNotificationName:klogin_notification object:nil];
}

- (void)logoutWith401 {
    
    if (!self.hasLogin) {
        return;
    }
    [[(AppDelegate*)[UIApplication sharedApplication].delegate root] popToRootViewControllerAnimated:YES];
    [self clearWhenLogout];
}

- (void)logoutSuccessBlock:(LoginSuccessBlock)successBlock {
    
    [HttpRequest postURL:klogout paras:nil showProgress:YES successful:^(id  _Nullable result) {
        
        if (successBlock) {
            successBlock();
        }
    } failed:^(int code, NSString *errMsg) {
        
    }];
}

#pragma mark - 第三方登录

- (void)loginWithThirdParty:(ThirdPartyLogin)type successBlock:(LoginSuccessBlock)successBlock failedBlock:(LoginFailedBlock)failedBlock {
    
    self.thirdLoginSuccess = successBlock;
    self.thirdLoginFailed = failedBlock;
    if (type == TPL_WECHAT) {
        if ([WXApi isWXAppInstalled]) {
            SendAuthReq *req = [[SendAuthReq alloc] init];
            req.scope = @"snsapi_userinfo";
            req.state = @"";
            [WXApi sendAuthReq:req viewController:nil delegate:self];
        }else {
            [TipManager showTip:@"未安装微信"];
        }
    }else {
        
        if (!_oauth) {
            self.oauth = [[TencentOAuth alloc] initWithAppId:@"101500851" andDelegate:self];
            _oauth.authMode = kAuthModeClientSideToken;
        }
        [_oauth authorize:@[kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO] inSafari:NO];
    }
}

- (void)thirdPartyBindPhone:(NSString *)phone code:(NSString *)code connect_id:(NSString *)connect_id successBlock:(LoginSuccessBlock)successBlock {
    
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:kbinding_phone paras:@{@"mobile": phone, @"code": code, @"connect_id": connect_id} showProgress:YES successful:^(id  _Nullable result) {
        [weakself loginWithDic:result[@"data"]];
        if (successBlock) {
            successBlock();
        }
    } failed:nil];
}

- (void)showThirdPartyBindPhoneController:(NSString *)connect_id {
    
    ChangePhoneSecondViewController *con = [[ChangePhoneSecondViewController alloc] init];
    con.isThirdLogin = YES;
    con.connect_id = connect_id;
    [[(AppDelegate*)[UIApplication sharedApplication].delegate root] pushViewController:con animated:NO];
}

- (void)onReq:(BaseReq *)req {
    
}

- (void)onResp:(BaseResp *)resp {
    
    __weak typeof(self) weakself = self;
    SendAuthResp *sresp = (SendAuthResp*)resp;
    if (sresp.code && sresp.code.length > 0) {
        
        [HttpRequest postURL:kthird_login paras:@{@"client": @"wechat", @"code": sresp.code} showProgress:YES successful:^(id  _Nullable result) {
            //"connect_id" = 3;
            NSLog(@"%@", result);
            
            if (result[@"data"][@"connect_id"] == nil || (NSNull*)result[@"data"][@"connect_id"] == [NSNull null]) {
                
                [weakself loginWithDic:result[@"data"]];
            }else {
                [weakself showThirdPartyBindPhoneController:result[@"data"][@"connect_id"]];
            }
            if (weakself.thirdLoginSuccess) {
                weakself.thirdLoginSuccess();
            }
        } failed:^(int code, NSString *errMsg) {
            if (weakself.thirdLoginFailed) {
                weakself.thirdLoginFailed();
            }
        }];
    }
}

#pragma mark - qq

- (void)tencentDidLogin {
    [self.oauth getUserInfo];
}

- (void)tencentDidNotLogin:(BOOL)cancelled {
    if (!cancelled) {
        [TipManager showTip:@"授权失败"];
    }
}

- (void)tencentDidNotNetWork {
    [TipManager showTip:@"网络连接失败"];
}

- (void)getUserInfoResponse:(APIResponse *)response {
    NSLog(@"%@", response);
    if (response.jsonResponse != nil && (NSNull *)response.jsonResponse != [NSNull null]) {
        NSDictionary *info = response.jsonResponse;
        NSString *client = @"qq";
        NSString *openid = self.oauth.openId;
//        NSString *unionid = self.oauth.unionid;
        NSString *access_token = self.oauth.accessToken;
        NSString *nickname = info[@"nickname"];
        NSString *avatar = info[@"figureurl_qq_2"];
        NSString *gender = @"0";
        if ([info[@"gender"] isEqualToString:@"男"]) {
            gender = @"1";
        }else if ([info[@"gender"] isEqualToString:@"女"]) {
            gender = @"2";
        }
        NSDictionary *para = @{@"client": client, @"openid": openid, @"access_token": access_token, @"nickname": nickname, @"avatar": avatar, @"gender": gender};
        
        __weak typeof(self) weakself = self;
        [HttpRequest postURL:kqq_login paras:para showProgress:YES successful:^(id  _Nullable result) {
            //"connect_id" = 3;
            NSLog(@"%@", result);
            
            if (result[@"data"][@"connect_id"] == nil || (NSNull*)result[@"data"][@"connect_id"] == [NSNull null]) {
                
                [weakself loginWithDic:result[@"data"]];
            }else {
                [weakself showThirdPartyBindPhoneController:result[@"data"][@"connect_id"]];
            }
            if (weakself.thirdLoginSuccess) {
                weakself.thirdLoginSuccess();
            }
        } failed:^(int code, NSString *errMsg) {
            if (weakself.thirdLoginFailed) {
                weakself.thirdLoginFailed();
            }
        }];
    }else {
        [TipManager showTip:@"获取信息失败"];
    }
}

@end
